/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package playground.denis.thread_examples;


import java.lang.*;
import java.io.BufferedReader;
import java.io.File;

import java.io.FileReader;
import java.io.IOException;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * That one just gets the  lines and spawn some threads to process it 
 * @author makkalot
 * @licence GPLV2
 */
public class LineGetter extends Thread{
    
    int NUM_THREAD_SPAWN = 3; // how many to spawn ?
    
    private File fi = null;
    LineProcesser [] lips = new LineProcesser[NUM_THREAD_SPAWN];
    
    public List<String> wordList ;
    
    /**
     * 
     * @param fi Takes a file variable 
     */

    public LineGetter(File fi) {
        
        this.fi = fi;
        
        
       
    }
    
    /**
     * The line getter part here 
     * when ready notify one of them if no one end here 
     * 
     */
    @Override
    public void run(){
        wordList =  new LinkedList<String>();
        
         for (int i = 0; i< NUM_THREAD_SPAWN; i++){
            lips[i]= new LineProcesser(wordList, i);
            lips[i].start();
        
        }
       
        
        synchronized(wordList){
        
        try {
        BufferedReader bfin = new BufferedReader(new FileReader(fi));
        String liner;
       
        List<Thread> mythreads = new ArrayList <Thread>();
        
        while ((liner= bfin.readLine())!=null){
              wordList.add(liner.toString());
              System.out.println("I have processed a line and i will notify the others!");
              wordList.notifyAll();
        }
        
        // here all the shit ends so we should kill the threads
        for (int thread = 0 ; thread<lips.length; thread++ )
            lips[thread].interrupt();
        
        
        }
        
        catch(IOException ex){
        System.err.println(ex);
        }
        
        }
    }
    
    
    

}
